/*=============================================================================

  Library: CFS

  Copyright (c) German Cancer Research Center,
    Division of Medical and Biological Informatics

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

=============================================================================*/

#include <QMutex>

#include "CFSPluginFrameworkContext_p.h"
#include "CFSPlugin_p.h"
#include "CFSPluginConstants.h"
#include "CFSServiceFactory.h"
#include "CFSServiceRegistration.h"
#include "CFSServiceRegistration_p.h"
#include "CFSServices_p.h"
#include "CFSServiceSlotEntry_p.h"

#include <stdexcept>

//----------------------------------------------------------------------------
CFSServiceRegistration::CFSServiceRegistration()
  : d_ptr(0)
{

}

//----------------------------------------------------------------------------
CFSServiceRegistration::CFSServiceRegistration(const CFSServiceRegistration& reg)
  : d_ptr(reg.d_ptr)
{
  if (d_func()) d_func()->ref.ref();
}

//----------------------------------------------------------------------------
CFSServiceRegistration::CFSServiceRegistration(CFSServiceRegistrationPrivate* registrationPrivate)
  : d_ptr(registrationPrivate)
{
  if(d_func()) d_func()->ref.ref();
}

//----------------------------------------------------------------------------
CFSServiceRegistration::CFSServiceRegistration(CFSPluginPrivate* plugin, QObject* service,
                    const CFSDictionary& props)
  : d_ptr(new CFSServiceRegistrationPrivate(plugin, service, props))
{

}

//----------------------------------------------------------------------------
CFSServiceRegistration::operator bool() const
{
  return d_func();
}

//----------------------------------------------------------------------------
CFSServiceRegistration& CFSServiceRegistration::operator=(int null)
{
  if (null == 0)
  {
    if (d_func() && !d_func()->ref.deref())
    {
      delete d_ptr;
    }
    d_ptr = 0;
  }
  return *this;
}

//----------------------------------------------------------------------------
CFSServiceRegistration::~CFSServiceRegistration()
{
  if (d_func() && !d_func()->ref.deref())
    delete d_ptr;
}

//----------------------------------------------------------------------------
CFSServiceReference CFSServiceRegistration::getReference() const
{
  Q_D(const CFSServiceRegistration);

  if (!d) throw CFSIllegalStateException("CFSServiceRegistration object invalid");
  if (!d->available) throw CFSIllegalStateException("Service is unregistered");

  return d->reference;
}

//----------------------------------------------------------------------------
void CFSServiceRegistration::setProperties(const CFSDictionary& props)
{
  Q_D(CFSServiceRegistration);
  if (!d) throw CFSIllegalStateException("CFSServiceRegistration object invalid");

  QMutexLocker lock(&d->eventLock);

  QSet<CFSServiceSlotEntry> before;
  // TBD, optimize the locking of services
  {
    QMutexLocker lock2(&d->plugin->fwCtx->globalFwLock);
    QMutexLocker lock3(&d->propsLock);

    if (d->available)
    {
      // NYI! Optimize the MODIFIED_ENDMATCH code
      int old_rank = d->properties.value(CFSPluginConstants::SERVICE_RANKING).toInt();
      before = d->plugin->fwCtx->listeners.getMatchingServiceSlots(d->reference, false);
      QStringList classes = d->properties.value(CFSPluginConstants::OBJECTCLASS).toStringList();
      qlonglong sid = d->properties.value(CFSPluginConstants::SERVICE_ID).toLongLong();
      d->properties = CFSServices::createServiceProperties(props, classes, sid);
      int new_rank = d->properties.value(CFSPluginConstants::SERVICE_RANKING).toInt();
      if (old_rank != new_rank)
      {
        d->plugin->fwCtx->services->updateServiceRegistrationOrder(*this, classes);
      }
    }
    else
    {
      throw CFSIllegalStateException("Service is unregistered");
    }
  }
  d->plugin->fwCtx->listeners.serviceChanged(
      d->plugin->fwCtx->listeners.getMatchingServiceSlots(d->reference),
      CFSServiceEvent(CFSServiceEvent::MODIFIED, d->reference), before);

  d->plugin->fwCtx->listeners.serviceChanged(
      before,
      CFSServiceEvent(CFSServiceEvent::MODIFIED_ENDMATCH, d->reference));
}

//----------------------------------------------------------------------------
void CFSServiceRegistration::unregister()
{
  Q_D(CFSServiceRegistration);
  if (!d) throw CFSIllegalStateException("CFSServiceRegistration object invalid");

  if (d->unregistering) return; // Silently ignore redundant unregistration.
  {
    QMutexLocker lock(&d->eventLock);
    if (d->unregistering) return;
    d->unregistering = true;

    if (d->available)
    {
      if (d->plugin)
      {
        d->plugin->fwCtx->services->removeServiceRegistration(*this);
      }
    }
    else
    {
      throw CFSIllegalStateException("Service is unregistered");
    }
  }

  if (d->plugin)
  {
     d->plugin->fwCtx->listeners.serviceChanged(
         d->plugin->fwCtx->listeners.getMatchingServiceSlots(d->reference),
         CFSServiceEvent(CFSServiceEvent::UNREGISTERING, d->reference));
  }

  {
    QMutexLocker lock(&d->eventLock);
    {
      QMutexLocker lock2(&d->propsLock);
      d->available = false;
      if (d->plugin)
      {
        for (QHashIterator<QSharedPointer<CFSPlugin>, QObject*> i(d->serviceInstances); i.hasNext();)
        {
          QObject* obj = i.next().value();
          try
          {
            // NYI, don't call inside lock
            qobject_cast<CFSServiceFactory*>(d->service)->ungetService(i.key(),
                                                                       *this,
                                                                       obj);
          }
          catch (const CFSException& ue)
          {
            CFSPluginFrameworkEvent pfwEvent(CFSPluginFrameworkEvent::PLUGIN_ERROR, d->plugin->q_func(), ue);
            d->plugin->fwCtx->listeners.emitFrameworkEvent(pfwEvent);
          }
        }
      }
      d->plugin = 0;
      d->dependents.clear();
      d->service = 0;
      d->serviceInstances.clear();
      d->reference = 0;
      d->unregistering = false;
    }
  }
}

//----------------------------------------------------------------------------
bool CFSServiceRegistration::operator<(const CFSServiceRegistration& o) const
{
  Q_D(const CFSServiceRegistration);
  if (!d) return true;
  return d->reference <(o.d_func()->reference);
}

//----------------------------------------------------------------------------
bool CFSServiceRegistration::operator==(const CFSServiceRegistration& registration) const
{
  Q_D(const CFSServiceRegistration);
  return d == registration.d_func();
}

//----------------------------------------------------------------------------
CFSServiceRegistration& CFSServiceRegistration::operator=(const CFSServiceRegistration& registration)
{
  CFSServiceRegistrationPrivate* curr_d = d_func();
  d_ptr = registration.d_ptr;
  if (d_ptr) d_ptr->ref.ref();

  if (curr_d && !curr_d->ref.deref())
    delete curr_d;

  return *this;
}

//----------------------------------------------------------------------------
uint qHash(const CFSServiceRegistration& serviceReg)
{
  return qHash(serviceReg.d_func());
}
